package com.yjt.fresh.utils;

import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.StateListDrawable;
import android.net.Uri;
import android.os.Environment;
import android.text.InputFilter;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

/**
 * @author jasonGong
 * @description 描述 :
 * @projectName tuanXiang
 * @date 创建时间：2015年11月6日 下午4:52:21
 * @parameter
 * @return
 **/
public class CommonsToolsHelper {

    /**
     * 动态设置控件的边框颜色，大小，填充颜色，圆角弧度
     *
     * @param v
     * @param solidColor  内容填充颜色
     * @param corners     圆角弧度
     * @param strokeColor 边框颜色
     * @param strokeWidth 边框宽度
     */
    public static void setShapeBorder(View v, int solidColor, int corners, int strokeColor, int strokeWidth) {
        GradientDrawable gd = (GradientDrawable) v.getBackground();
        gd.setColor(solidColor);
        gd.setCornerRadius(corners);
        gd.setStroke(strokeWidth, strokeColor);
    }

    /**
     * 获得状态栏的高度
     *
     * @param context
     * @return
     */
    public static int getStatusHeight(Context context) {
        int result = 0;
        int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            result = context.getResources().getDimensionPixelSize(resourceId);
        }
        return result;
    }

    /**
     * 图片转换成字节
     *
     * @author Gxcheng
     * @time 2016/9/2 0002 17:25
     */
    public static byte[] Bitmap2Bytes(Bitmap bm) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
        return baos.toByteArray();
    }

    /**
     * 判断参数是否为空
     *
     * @param str
     * @return
     */
    public static boolean isEmty(String str) {
        if (str == null || str.length() == 0)
            return true;
        else
            return false;

    }

    /**
     * 判断号码合法性
     *
     * @author ZFL
     * @time 2016/9/8 10:53
     */
    public static boolean isPhoneNum(String num) {
        return isMobileNum(num) | isFixedPhone(num);
    }

    /**
     * 判断手机号码的合法性
     *
     * @param num
     * @return
     */
    public static boolean isMobileNum(String num) {
        Pattern p = Pattern.compile("^(1[3,4,5,7,8][0-9])\\d{8}$");
        Matcher m = p.matcher(num);
        return m.matches();
    }

    /**
     * 判断邮箱输入是否合法
     *
     * @author Gxcheng
     * @time 2016/9/27 0027 14:39
     */
    public static boolean isEmail(String strEmail) {
        String strPattern = "^\\s*\\w+(?:\\.{0,1}[\\w-]+)*@[a-zA-Z0-9]+(?:[-.][a-zA-Z0-9]+)*\\.[a-zA-Z]+\\s*$";
        Pattern p = Pattern.compile(strPattern);
        Matcher m = p.matcher(strEmail);
        return m.matches();
    }

    /**
     * 判断是否为固定电话号码
     *
     * @param number
     * @return
     */
    public static boolean isFixedPhone(String number) {
        Matcher match = Pattern.compile("(\\d{2,5}-\\d{7,8}(-\\d{1,})?)|(13\\d{9})|(159\\d{8})").matcher(number);
        return match.matches();
    }

    /**
     * 判断用户输入的密码是否为字母
     *
     * @author Gxcheng
     * @time 2016/8/15 0015 14:19
     */
    public static boolean isLetterAndNumber(String str) {
        Pattern p = Pattern.compile("[A-Za-z0-9]*");
        Matcher m = p.matcher(str);
        return m.matches();
    }


    /**
     * 检查设备是否存在SDCard的工具方法
     */
    public static boolean hasSdcard() {
        String state = Environment.getExternalStorageState();
        if (state.equals(Environment.MEDIA_MOUNTED)) {
            // 有存储的SDCard
            return true;
        } else {
            return false;
        }
    }

    /**
     * 动态设置ListView的高度
     *
     * @param listView
     */
    public static void setListViewHeight(ListView listView) {
        if (listView == null) return;
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            // pre-condition
            return;
        }
        int totalHeight = 0;
        for (int i = 0; i < listAdapter.getCount(); i++) {
            View listItem = listAdapter.getView(i, null, listView);
            listItem.measure(0, 0);
            totalHeight += listItem.getMeasuredHeight();
        }
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        listView.setLayoutParams(params);
    }

    /**
     * 根据手机的分辨率从 dip 的单位 转成为 px(像素)
     */
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
     */
    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    /**
     * 将sp值转换为px值，保证文字大小不变
     *
     * @param spValue （DisplayMetrics类中属性scaledDensity）
     * @return
     */
    public static int sp2px(Context context, float spValue) {
        final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
        return (int) (spValue * fontScale + 0.5f);
    }

    /**
     * 获取屏幕的宽度
     *
     * @param context
     * @return
     */
    public static int getWindowWidth(Context context) {
        WindowManager wm = (WindowManager) context.getSystemService(context.WINDOW_SERVICE);
        int width = wm.getDefaultDisplay().getWidth();
        return width;
    }

    /**
     * 获取屏幕的高度
     */
    public static int getWindowHeight(Context context) {
        WindowManager wm = (WindowManager) context.getSystemService(context.WINDOW_SERVICE);
        int height = wm.getDefaultDisplay().getHeight();
        return height;
    }

    /**
     * 从字符串中提取数字
     */
    public static String getNumberFromStr(String str) {
        String regEx = "[^0-9]";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(str);
        return m.replaceAll("").trim();
    }

    /*判断输入的是否是数字*/
    public static boolean isNumber(String str) {
        Pattern p = Pattern.compile("[0-9]*");
        Matcher m = p.matcher(str);
        return m.matches();
    }

    /**
     * 判定输入汉字
     *
     * @param c
     * @return
     */
    public static boolean isChinese(char c) {
        Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
        if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A || ub == Character.UnicodeBlock.GENERAL_PUNCTUATION || ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS) {
            return true;
        }
        return false;
    }


    /**
     * 禁止EditText输入空格和换行符
     *
     * @param editText EditText输入框
     */
    public static void setEditTextInputSpace(EditText editText) {
        InputFilter filter = new InputFilter() {
            @Override
            public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
                if (source.equals(" ") || source.toString().contentEquals("\n")) {
                    return "";
                } else {
                    return null;
                }
            }
        };
        editText.setFilters(new InputFilter[]{filter});
    }
    /**
     * 检测String是否全是中文
     *
     * @param name
     * @return
     */
    public static boolean checkNameChinese(String name) {
        boolean res = true;
        char[] cTemp = name.toCharArray();
        for (int i = 0; i < name.length(); i++) {
            if (!isChinese(cTemp[i])) {
                res = false;
                break;
            }
        }
        return res;
    }

    /**
     * 描述：判断字符串是否只含字母和汉字，也可以不限制数字 <br>
     * 作者：zfl <br>
     * 日期：2017/3/25 17:30
     */
    public static String noSpecialStringFilter(String str, boolean allowNumber) throws PatternSyntaxException {
        String regEx = "[\\p{Ll}\\p{Lu}\\u4E00-\\u9FA5 ]+";
        if (allowNumber) regEx = "[\\p{P}\\p{N}\\p{Ll}\\p{Lu}\\u4E00-\\u9FA5 ]+";
        return str != null ? (str.matches(regEx) ? str : "") : "";
    }

    /**
     * 将数字控制为2位，如果是1，就在前面加0
     *
     * @param num
     * @return
     */
    public static String formate2(int num) {
        DecimalFormat df = new DecimalFormat("00");
        String str2 = df.format(num);
        return str2;
    }

    /**
     * 描述：将字符串转为精确的double <br>
     * 作者：zfl <br>
     * 日期：2017/3/8 13:53
     */
    public static double stringToDouble(String num) {
        DecimalFormat dc = new DecimalFormat();
        double target = 0;
        if (num.contains(".")) {
            try {
                target = (Double) dc.parse(num);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        } else {
            target = Double.parseDouble(num);
        }
        return target;
    }

    /**
     * 描述：从一个文件的绝对路径string中获取文件名 <br>
     * 作者：zfl <br>
     * 日期：2017/3/8 14:51
     */
    public static String getFileNameFromFilePath(String filePath) {
        String fileName = "";
        fileName = filePath.substring(filePath.lastIndexOf("/") + 1, filePath.length());
        return fileName;
    }

    /**
     * 描述：将2011-07-02转为2011年07月02日的字符串返回，并且可以控制是否返回日份 <br>
     * 作者：zfl <br>
     * 日期：2017/3/18 14:27
     */
    public static String getChineseDateStr(String date, boolean needDay) {
        if (TextUtils.isEmpty(date)) return null;
        String[] strs = date.split("-");
        String targetDate = "";
        targetDate = targetDate + strs[0] + "年";
        targetDate = targetDate + strs[1] + "月";
        if (needDay) {
            targetDate = targetDate + strs[2] + "日";
        }
        return targetDate;
    }

    /**
     * 获取明天的日期
     *
     * @return
     */
    public static String getNextDay() {
        String str = "";
        SimpleDateFormat sdf = new SimpleDateFormat("MM-dd");
        Calendar lastDate = Calendar.getInstance();
        int nextDay = lastDate.get(Calendar.DAY_OF_MONTH) + 1;
        lastDate.set(Calendar.DATE, nextDay);// 设置日期为后一天 
        str = sdf.format(lastDate.getTime());
        return str;
    }

    /**
     * 获取今天的日期
     *
     * @return
     */
    public static String getCurrentDay() {
        String str = "";
        SimpleDateFormat sdf = new SimpleDateFormat("MM-dd");
        Calendar lastDate = Calendar.getInstance();
        str = sdf.format(lastDate.getTime());
        return str;
    }

    /**
     * 获取今年
     *
     * @author Gxcheng
     * @time 2016/7/21 0021 16:46
     */
    public static String getThisYear() {
        String str = "";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
        Calendar lastDate = Calendar.getInstance();
        str = sdf.format(lastDate.getTime());
        return str;
    }

    public static String formatyyyy_MM_ddHHmmss(long dateStr) {
        Date date = new Date(dateStr);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return sdf.format(date);
    }

    /**
     * 格式日期
     *
     * @author Gxcheng
     * @time 2016/9/22 0022 12:07
     */
    public static String getCurrentTime() {
        String str = "";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        Calendar lastDate = Calendar.getInstance();
        str = sdf.format(lastDate.getTime());
        return str;
    }

    /**
     * 格式日期
     *
     * @author Gxcheng
     * @time 2016/9/22 0022 12:07
     */
    public static String getTimeyyyy_mm_dd() {
        String str = "";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar lastDate = Calendar.getInstance();
        str = sdf.format(lastDate.getTime());
        return str;
    }

    /**
     * 获取控件在屏幕中的坐标位置
     *
     * @param v
     * @return
     */
    public static int[] getXYInScreen(View v) {
        int[] location = new int[2];
        v.getLocationInWindow(location);
        return location;
    }

    /**
     * 获取送餐时间段
     *
     * @param openTime  开门时间
     * @param closeTime 关门时间
     * @return
     */
    public static List<String> getRoomTime(int openTime, int closeTime) {
        List<String> list = new ArrayList<>();
        List<String> timeList = new ArrayList<>();
        String timeStr = "";
        for (int i = openTime; i < closeTime; i++) {
            for (int j = 0; j < 4; j++) {
                if (j * 15 == 0) {
                    timeStr = formate2(i) + ":00";
                } else {
                    timeStr = formate2(i) + ":" + j * 15;
                }

                list.add(timeStr);
            }
            if (i == closeTime - 1) {
                list.add(formate2(closeTime) + ":00");
            }
        }
        for (int i = 0; i < list.size(); i++) {

            if (i + 1 == list.size()) {

            } else {
                timeStr = list.get(i) + "-" + list.get(i + 1);
            }
            timeList.add(timeStr);
        }
        return timeList;
    }

    /*刷新日期*/
    public static String friendlyTime(Date time) {
        //获取time距离当前的秒数
        int ct = (int) ((System.currentTimeMillis() - time.getTime()) / 1000);

        if (ct == 0) {
            return "刚刚";
        }

        if (ct > 0 && ct < 60) {
            return ct + "秒前";
        }

        if (ct >= 60 && ct < 3600) {
            return Math.max(ct / 60, 1) + "分钟前";
        }
        if (ct >= 3600 && ct < 86400)
            return ct / 3600 + "小时前";
        if (ct >= 86400 && ct < 2592000) { //86400 * 30
            int day = ct / 86400;
            return day + "天前";
        }
        if (ct >= 2592000 && ct < 31104000) { //86400 * 30
            return ct / 2592000 + "月前";
        }
        return ct / 31104000 + "年前";
    }

    /**
     * 将阿拉伯数字转换成中文数字
     *
     * @author Gxcheng
     * @time 2016/7/20 0020 8:52
     */
    public static String numberToChinese(int d) {
//        String[] str = { "零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖" };
        String[] str = {"零", "一", "二", "三", "四", "五", "六", "七", "八", "九"};
//        String ss[] = new String[] { "元", "拾", "佰", "仟", "万", "拾", "佰", "仟", "亿" };
        String ss[] = new String[]{"", "十", "百", "千", "万", "十", "百", "千", "亿"};
        String s = String.valueOf(d);
        System.out.println(s);
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < s.length(); i++) {
            String index = String.valueOf(s.charAt(i));
            sb = sb.append(str[Integer.parseInt(index)]);
        }
        String sss = String.valueOf(sb);
        int i = 0;
        for (int j = sss.length(); j > 0; j--) {
            sb = sb.insert(j, ss[i++]);
        }
        return sb.toString();
    }

    public static String formatNumber(double d) {
        DecimalFormat df = new DecimalFormat("#,###,##0");
        return df.format(d);

    }


    /**
     * 获取通过相机拍照保存路径
     *
     * @author Gxcheng
     * @time 2016/8/9 0009 15:37
     */
    public static String getImgFileName() {
        String name = new DateFormat().format("GL_IMG_yyyyMMdd_hhmmss", Calendar.getInstance(Locale.CHINA)) + ".jpg";
//		String fileName = "sdcard/glImage/"+name;
        return name;
    }

    /**
     * @return
     * @author lucm
     * @detail 产生六位数的随机数
     * @data 2016-06-27
     * @version 1.0
     * @since gbapp1.0
     */
    public static String getRandomAutoCode() {
        int i = (int) ((Math.random() * 9 + 1) * 100000);//生成六位数的整数
        String str = String.valueOf(i);//转换成String类型的值
        System.out.println(str);
        return str;
    }

    /**
     * 图片文件压缩,有可能会报OOM错误
     *
     * @author ZFL
     * @time 2016/8/22 14:01
     */
    public static File compressImgFile(File file) {
        String path = file.getPath();
        File outputFile = null;
        try {
            Bitmap bitmap = BitmapFactory.decodeFile(path);
            outputFile = new File(createImageFile().getPath());
            FileOutputStream fos = null;
            //目前只采用质量压缩
            Bitmap targetBitmap = compressQuality(bitmap);
            fos = new FileOutputStream(outputFile);
            targetBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.close();
            if (!bitmap.isRecycled()) {
                bitmap.recycle();
            } else {
                File tempFile = outputFile;
                outputFile = new File(createImageFile().getPath());
                copyFileUsingFileChannels(tempFile, outputFile);
            }
            if (!targetBitmap.isRecycled()) {
                targetBitmap.recycle();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (OutOfMemoryError error) {
            Log.e("tag", "OOM happened!");
        }
        return outputFile;
    }

    /**
     * 根据bitmap压缩图片质量
     *
     * @param bitmap 未压缩的bitmap
     * @return 压缩后的bitmap
     */
    public static Bitmap compressQuality(Bitmap bitmap) {
        ByteArrayOutputStream bOut = new ByteArrayOutputStream();
        int beginRate = 100;
        //第一个参数 ：图片格式 ，第二个参数： 图片质量，100为最高，0为最差  ，第三个参数：保存压缩后的数据的流
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bOut);
        while (bOut.size() > 500) {  //如果压缩后大于5MB，则提高压缩率，重新压缩
            beginRate -= 10;
            bOut.reset();
            bitmap.compress(Bitmap.CompressFormat.JPEG, beginRate, bOut);
        }
        ByteArrayInputStream bInt = new ByteArrayInputStream(bOut.toByteArray());
        Bitmap newBitmap = BitmapFactory.decodeStream(bInt);
        try {
            bOut.close();
            bInt.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (newBitmap != null) {
            return newBitmap;
        } else {
            return bitmap;
        }
    }


    public static Uri createImageFile() {
        // Create an image file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        File storageDir = Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_PICTURES);
        File image = null;
        try {
            image = File.createTempFile(
                    imageFileName,  /* prefix */
                    ".jpg",         /* suffix */
                    storageDir      /* directory */
            );
        } catch (IOException e) {
            e.printStackTrace();
        }
        // Save a file: path for use with ACTION_VIEW intents
        return Uri.fromFile(image);
    }

    public static void copyFileUsingFileChannels(File source, File dest) {
        FileChannel inputChannel = null;
        FileChannel outputChannel = null;
        try {
            try {
                inputChannel = new FileInputStream(source).getChannel();
                outputChannel = new FileOutputStream(dest).getChannel();
                outputChannel.transferFrom(inputChannel, 0, inputChannel.size());
            } catch (IOException e) {
                e.printStackTrace();
            }
        } finally {
            try {
                inputChannel.close();
                outputChannel.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 当处于编辑模式时，用户如果上次的图片列表为空，传递一个简单的文本文件代替之
     *
     * @author ZFL
     * @time 2016/8/29 16:00
     */
    public static File getEmptyLabelFile(Context context) {
//        File dataPathFile = Environment.getDataDirectory();
//        String dataPath = dataPathFile.toString();
        File file = new File(context.getCacheDir().getAbsolutePath() + File.separator, "Globalives");
        try {
            file.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return file;
    }

    /**
     * 需要权限:android.permission.GET_TASKS
     * 判断activity是否在前台运行
     *
     * @param context
     * @return
     */
    public boolean isApplicationBroughtToBackground(Context context) {
        ActivityManager am = (ActivityManager) context
                .getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> tasks = am.getRunningTasks(1);
        if (tasks != null && !tasks.isEmpty()) {
            ComponentName topActivity = tasks.get(0).topActivity;
            if (!topActivity.getPackageName().equals(context.getPackageName())) {
                return true;
            }
        }
        return false;
    }

    /**
     * 获取当前版本信息
     *
     * @author Gxcheng
     * @time 2016/9/27 0027 10:41
     */
    public static PackageInfo getPackageInfo(Context context) {
        PackageInfo pi = null;

        try {
            PackageManager pm = context.getPackageManager();
            pi = pm.getPackageInfo(context.getPackageName(),
                    PackageManager.GET_CONFIGURATIONS);

            return pi;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return pi;
    }

    /**
     * 获取保存文件的路径的file
     *
     * @param folderName 文件夹名称
     * @return
     */
    public static File getSaveOutFile(String folderName) {
        String filePath = Environment.getExternalStorageDirectory().getPath()
                + File.separator + folderName + File.separator + System.currentTimeMillis() + ".jpg";
        File dirFile = new File(filePath);
        if (!dirFile.getParentFile().exists())
            dirFile.getParentFile().mkdirs();
        return dirFile;
    }

    /**
     * 设置控件的边框，颜色，圆角，填充色<br>
     * 如果不想要边框，将边框宽度设置为0即可,edit by ZFL 2017.01.23
     */
    public static GradientDrawable setGradientDr(Context context, int strokeWidth, int roundRadius, int strokeColorCId, int fillColorCId) {
        GradientDrawable gd = new GradientDrawable();
        int fillColor = Color.parseColor(context.getResources().getString(fillColorCId));//内部填充颜色
        gd.setColor(fillColor);
        gd.setCornerRadius(roundRadius);
        if (strokeWidth != 0) {
            int strokeColor = Color.parseColor(context.getResources().getString(strokeColorCId));//边框颜色
            gd.setStroke(strokeWidth, strokeColor);
        }
        return gd;
    }


    /**
     * 设置控件的边框，颜色，圆角（可自定义四个角度不同弧度），填充色
     *
     * @param context
     * @param strokeWidth    边框宽度
     * @param radii          圆角
     * @param strokeColorCId 边框颜色
     * @param fillColorCId   内部填充颜色
     * @return
     */
    public static GradientDrawable setGradientDr(Context context, int strokeWidth, float[] radii, int strokeColorCId, int fillColorCId) {
        GradientDrawable gd = new GradientDrawable();
        int fillColor = Color.parseColor(context.getResources().getString(fillColorCId));//内部填充颜色
        gd.setColor(fillColor);
        gd.setCornerRadii(radii);
        if (strokeWidth != 0) {
            int strokeColor = Color.parseColor(context.getResources().getString(strokeColorCId));//边框颜色
            gd.setStroke(strokeWidth, strokeColor);
        }
        return gd;
    }

    /**
     * 代码设置selector选择器
     *
     * @param norGradientDrable   默认状态下的shape
     * @param pressGradientDrable 按下状态的shape
     * @return
     */
    public static StateListDrawable setStateListDrawable(GradientDrawable norGradientDrable, GradientDrawable pressGradientDrable) {
        //状态选择器
        StateListDrawable stateListDrawable = new StateListDrawable();
        stateListDrawable.addState(new int[]{android.R.attr.state_pressed}, pressGradientDrable);
        stateListDrawable.addState(new int[]{}, norGradientDrable);
        return stateListDrawable;
    }

    /**
     * 判断输入的是否连续的数字
     *
     * @param str 输入的字符串
     * @return
     */
    public static boolean isContinuityNumber(String str) {
        String reg = "^.*\\d{5}.*$";
        if (str.matches(reg)) {
            return true;
        }
        return false;
    }

    /**
     * 米转换千米
     */
    public static String metersToKilometer(int meters) {
        String distanceStr = "";
        if (meters > 1000) {
            double dis = 0;
            dis = Math.round(meters / 100d) / 10d;
            distanceStr = dis + "千米";
        } else {
            distanceStr = meters + "米";
        }
        return distanceStr;
    }

    /*获取手机SD卡路径*/
    public static String getSdcardDir() {
        if (Environment.getExternalStorageState().equalsIgnoreCase(Environment.MEDIA_MOUNTED)) {
            return Environment.getExternalStorageDirectory().toString();
        }
        return null;
    }

    // string类型转换为long类型
    // strTime要转换的String类型的时间
    // formatType时间格式
    // strTime的时间格式和formatType的时间格式必须相同
    public static long stringToLong(String strTime) {
        String formatType = "yyyy-MM-dd HH:mm:ss";
        Date date = null; // String类型转成date类型
        try {
            date = stringToDate(strTime + " 00:00:00", formatType);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        if (date == null) {
            return 0;
        } else {
            long currentTime = dateToLong(date); // date类型转成long类型
            return currentTime;
        }
    }

    // date类型转换为long类型
    // date要转换的date类型的时间
    public static long dateToLong(Date date) {
        return date.getTime();
    }

    // string类型转换为date类型
    // strTime要转换的string类型的时间，formatType要转换的格式yyyy-MM-dd HH:mm:ss//yyyy年MM月dd日
    // HH时mm分ss秒，
    // strTime的时间格式必须要与formatType的时间格式相同
    public static Date stringToDate(String strTime, String formatType)
            throws ParseException {
        SimpleDateFormat formatter = new SimpleDateFormat(formatType);
        Date date = null;
        date = formatter.parse(strTime);
        return date;
    }

    public static String formatTimesTamp1(String dateStr) {
        Timestamp d = new Timestamp(System.currentTimeMillis());
        return Timestamp.valueOf(dateStr + " 00:00:00").toString();
    }

    /*生成工单号*/
    public static String CreateNo() {
        Random random = new Random();
        int a= (int) (Math.random()*9000+1000);
        String strRandom = String.valueOf(a); //生成编号
        String code = getCurrentTime() + strRandom;//形如
        return code;
    }

    /**
     * 是否包含数字
     * @param company
     * @return
     */
    public static boolean isContainNumber(String company) {

        Pattern p = Pattern.compile("[0-9]");
        Matcher m = p.matcher(company);
        if (m.find()) {
            return true;
        }
        return false;
    }

    /**
     * 使用正则表达式来判断字符串中是否包含字母
     * @param str 待检验的字符串
     * @return 返回是否包含
     * true: 包含字母 ;false 不包含字母
     */
    public static boolean isContainsLetter(String str) {
        String regex=".*[a-zA-Z]+.*";
        Matcher m=Pattern.compile(regex).matcher(str);
        return m.matches();
    }

    /**
     * 判断是否含有特殊字符
     *
     * @param str
     * @return true为包含，false为不包含
     */
    public static boolean isContainsSpecialChar(String str) {
        String regEx = "[ _`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]|\n|\r|\t";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(str);
        return m.find();
    }


    /**
     * 获取当前本地apk的版本
     *
     * @param mContext
     * @return
     */
    public static int getVersionCode(Context mContext) {
        int versionCode = 0;
        try {
            //获取软件版本号，对应AndroidManifest.xml下android:versionCode
            versionCode = mContext.getPackageManager().
                    getPackageInfo(mContext.getPackageName(), 0).versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return versionCode;
    }

    public static double getTwoDecimal(double num) {
        DecimalFormat dFormat= new DecimalFormat("#.00");
        String yearString=dFormat.format(num);
        Double emp= Double.valueOf(yearString);
        return emp;
    }

}
